<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const cashMsg = '“-1”对应单位“永久”，只能充值一次<br/>“0次”，可无限次充值'
const cashTypes = [{
  value: '1',
  text: '年',
  extend: {
    cashNum: 1,
    readonly: true
  }
}, {
  value: '2',
  text: '天',
  extend: {
    cashNum: ''
  }
}, {
  value: '3',
  text: '次',
  extend: {
    cashNum: 0
  }
}, {
  value: '4',
  text: '永久',
  extend: {
    cashNum: -1,
    readonly: true
  }
}]
let globalData = []
// ----
const isNumber = /^\d+(\.{0,2}\d+){0,2}$/
const isInteger = /^-?\d+$/
// ----
const form = reactive({
  id: 0,
  tabName: 'fees_name',
  // ----
  key: '',
  name: '',
  amount: '',
  give: 0,
  isReadonly: cashTypes[0].extend.readonly,
  cashNum: cashTypes[0].extend.cashNum,
  cashType: cashTypes[0].value,
  cashTypeText: cashTypes[0].text,
  remark: '',
  // ----
  btnTxt: '',
  attr: '',
  val: '',
  // ----
  isOpenUse: true,
  // ----
  isUpdate: false
})

/* ---- */
const pickerCashType = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = () => {
  // --获取信息--
  const newItems = forSys.filter((item) => { return String(item.name) === form.tabName })
  if (Number(newItems.length) === 1) {
    form.id = newItems[0].id
    proxy.$Myfun.getJsonData(newItems[0].value, (resJson) => {
      globalData = resJson
      // ----
      resJson.some((item) => {
        if (String(item.id) === String(proxy.$route.query.id)) {
          form.key = item.id
          if (item.name) form.name = item.name
          if (item.amount) form.amount = item.amount
          if (item.give) form.give = item.give
          if (item.readonly) form.isReadonly = item.readonly
          if (item.num) form.cashNum = item.num
          if (item.type) form.cashType = item.type
          if (item.typeText) form.cashTypeText = item.typeText
          if (item.remark) form.remark = item.remark
          // ----
          if (item.btnTxt) form.btnTxt = item.btnTxt
          if (item.attr) form.attr = item.attr
          if (item.val) form.val = item.val
          form.isOpenUse = item.isOpenUse
          // ----
          form.isUpdate = true
        }
      })
    })
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const checkLimit = (event, reg, info) => {
  const curEL = event.currentTarget
  if (Number(curEL.value.length) === 0) return false
  if (!reg.test(curEL.value)) {
    if (info) proxy.$Myfun.forToast(layer.value, 'open', info)
    // ----
    curEL.value = ''
    curEL.dispatchEvent(new Event('input'))
  }
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 1,
        button: ['取消', '确定'],
        initData: cashTypes,
        yes: (result) => {
          form.cashTypeText = result[0].text
          form.cashType = result[0].value
          // ----
          form.isReadonly = result[0].extend.readonly
          form.cashNum = result[0].extend.cashNum
        }
      }
      proxy.$Myfun.isIndepth(pickerCashType.value, 'open', options)
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写项目名称')
    return false
  }
  if (Number(form.amount.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请设置充值金额')
    return false
  }
  if (Number(form.cashNum.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请设置计费周期')
    return false
  }
  if (Number(form.cashType.length) === 0 || Number(form.cashTypeText.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择计费周期类型')
    return false
  }
  if (Number(form.btnTxt.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写按钮文字')
    return false
  }
  // ----
  if (proxy.$route.query.id) {
    globalData.some((item) => {
      if (String(item.id) === String(proxy.$route.query.id)) {
        item.name = form.name
        item.amount = form.amount
        item.give = form.give
        item.readonly = form.isReadonly
        item.num = form.cashNum
        item.type = form.cashType
        item.typeText = form.cashTypeText
        item.remark = form.remark
        // ----
        item.btnTxt = form.btnTxt
        item.attr = form.attr
        item.val = form.val
        // ----
        item.isOpenUse = form.isOpenUse
      }
    })
  } else {
    globalData.push({
      id: form.key,
      name: form.name,
      amount: form.amount,
      give: form.give,
      readonly: form.isReadonly,
      num: form.cashNum,
      type: form.cashType,
      typeText: form.cashTypeText,
      remark: form.remark,
      // ----
      btnTxt: form.btnTxt,
      attr: form.attr,
      val: form.val,
      // ----
      isOpenUse: form.isOpenUse
    })
  }
  // ----
  const forValue = JSON.stringify(globalData)
  // ----
  let forType = 'post'
  let forUrl = 'system/create'
  let forData = {
    name: form.tabName,
    value: forValue,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (Number(form.id) > 0) {
    forType = 'patch'
    forUrl = 'system/update?id=' + form.id
    forData = {
      value: forValue,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>项目索引</i>
            <template v-if="form.isUpdate">
            <p class="xw-color-13 xw-flex-W1">{{form.key}}</p>
            </template>
            <template v-else>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="设置后不能修改" v-model.trim="form.key"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.key"></em></transition>
            </template>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>项目名称</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.name"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.name"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>充值金额</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.amount" @blur="checkLimit($event, isNumber, '请输入非负数')"/></p>
            <span>元</span><span>/</span><span>{{form.cashTypeText}}</span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.amount"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>优惠赠送</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.give" @blur="checkLimit($event, isNumber, '请输入非负数')"/></p>
            <span>个</span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.give"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>计费周期</i>
            <p class="xw-flex-W1"><input class="text" :class="{'xw-color-16': form.isReadonly}" type="text" placeholder="" v-model.trim="form.cashNum" @blur="checkLimit($event, isInteger, '请输入整数')" :readonly="form.isReadonly" :disabled="form.isReadonly"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="Number(form.cashNum) > 1"></em></transition>
            <div class="form-txt-type"><input class="text xw-act" type="text" placeholder="" v-model.trim="form.cashTypeText" @click="getAuditFun(1)" readonly unselectable="on" onfocus="this.blur()"/></div>
          </div>
          <div class="form-msg xw-color-16" v-html="cashMsg" v-if="cashMsg"></div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>按钮文字</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.btnTxt"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.btnTxt"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>字段名称</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.attr"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.attr"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>字段赋值</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.val"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.val"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>备注说明</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.remark"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align xw-flex-justify">
            <i>是否使用</i>
            <p class="uct-sel"><input type="checkbox" class="a-switch" v-model="form.isOpenUse"/></p>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerCashType"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.uct-sel { height: 3rem; overflow: visible; }
</style>